import random
import time
import influxdb_client
from influxdb_client.client.write_api import SYNCHRONOUS, ASYNCHRONOUS

DEFAULT_ORG = 'aigcode'

DEFAULT_BUCKET = 'learning_data'

DEFAULT_MEASUREMENT = 'learning_{}'


class InfluxdbMetricReport:

    def __init__(self, url,token,hash,prop :dict = dict(), org=DEFAULT_ORG,bucket = DEFAULT_BUCKET):
        client = influxdb_client.InfluxDBClient(url=url, token=token, org=org)
        bucket_api = client.buckets_api()

        if bucket_api.find_bucket_by_name(bucket) is None:
            bucket_api.create_bucket(bucket_name = bucket,org_id=org)

        self.client = client
        self.measurement = DEFAULT_MEASUREMENT.format(hash)
        self.org = org
        self.bucket = bucket
        self.prop = prop

    def log_metric(self, name, value,timestamp = None, tags: dict= dict(), _async = False):
        client = self.client
        measurement_name = self.measurement
        org = self.org
        bucket = self.bucket
        write_options = ASYNCHRONOUS if _async else SYNCHRONOUS
        prop = self.prop

        point = influxdb_client.Point(measurement_name=measurement_name)
        point.field(name, value)

        if isinstance(timestamp,float):
            point.time(int(timestamp * 1000_000))
        if isinstance(timestamp,int):
            point.time(timestamp)
        for tag in tags:
            point.tag(tag, tags[tag])
        for p in prop:
            point.tag(p, prop[p])
        client.write_api(write_options=SYNCHRONOUS).write(org=org, bucket=bucket, record=point)


